package pers.li.controller.goods;

import pers.li.service.GoodsService;
import pers.li.utils.JedisUtils;
import pers.li.utils.JsonUtil;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/goods/searchGoods.action")
public class SearchGoodsController extends HttpServlet {
    private final GoodsService goodsService = new GoodsService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Jedis jedis = JedisUtils.getJedis();
        String keyword = req.getParameter("keyword");
        List goods = null;
        if (jedis.exists(keyword)) {
            String res = jedis.get(keyword);
            goods = JsonUtil.parseObject(res, List.class);
        } else {
            goods = goodsService.getGoodsByKeyword(keyword);
            jedis.set(keyword, JsonUtil.toJsonString(goods));
            jedis.expire(keyword, 60);
        }
        req.setAttribute("goods", goods);

        req.getRequestDispatcher("search_goods.jsp").forward(req, resp);
    }
}
